  <template>
    <Dialog :title="dialogTitle" v-model="dialogVisible">
      <el-form
        ref="formRef"
        :model="formData"
        :rules="formRules"
        label-width="100px"
        v-loading="formLoading"
      >
        <el-form-item label="资产名称" prop="assetName">
          <el-select
            v-model="formData.assetName"
            placeholder="请选择资产名称"
            filterable
            clearable
            class="w-100%"
            @change="handleAssetChange"
          >
            <el-option
              v-for="asset in assetList"
              :key="asset.id"
              :label="asset.assetName"
              :value="asset.assetName"
            />
          </el-select>
        </el-form-item>
        <el-form-item label="维修日期" prop="repairDate">
          <el-date-picker
            v-model="formData.repairDate"
            type="date"
            value-format="x"
            placeholder="选择维修日期"
          />
        </el-form-item>
        <el-form-item label="维修费用" prop="repairCost">
          <el-input v-model="formData.repairCost" placeholder="请输入维修费用" />
        </el-form-item>

        <el-form-item label="使用人员" prop="userId">
          <UserSelect @node-change="handleNodeChange" v-model="formData.userId"  />
        </el-form-item>

        <el-form-item label="维修原因" prop="repairReason">
          <el-input v-model="formData.repairReason" placeholder="请输入维修原因" type="textarea" :rows="3" />
        </el-form-item>
      </el-form>
      <template #footer>
        <el-button @click="submitForm" type="primary" :disabled="formLoading">确 定</el-button>
        <el-button @click="dialogVisible = false">取 消</el-button>
      </template>
    </Dialog>
  </template>

  <script setup lang="ts">
  import { AssetRepairApi, AssetRepairVO } from '@/api/oa/assetrepair'
  import UserSelect from '@/views/system/user/UserSelect.vue'
  import { AssetInfoApi } from '@/api/oa/assetinfo'

  import { ref } from 'vue'

  defineOptions({ name: 'AssetRepairForm' })

  const { t } = useI18n() // 国际化
  const message = useMessage() // 消息弹窗


  const dialogVisible = ref(false) // 弹窗的是否展示
  const dialogTitle = ref('') // 弹窗的标题
  const formLoading = ref(false) // 表单的加载中：1）修改时的数据加载；2）提交的按钮禁用
  const formType = ref('') // 表单的类型：create - 新增；update - 修改
  const formData = ref({
    id: undefined,
    assetName: undefined,
    assetCategory: undefined,
    assetBrand: undefined,
    model: undefined,
    repairDate: undefined,
    repairCost: undefined,
    repairReason: undefined,
    userId: undefined,
    userName: undefined,
    recordTime: undefined,
  })
  const formRules = reactive({
    assetName: [{ required: true, message: '资产名称不能为空', trigger: 'blur' }],
    assetCategory: [{ required: true, message: '资产分类不能为空', trigger: 'change' }],
    assetBrand: [{ required: true, message: '资产品牌不能为空', trigger: 'change' }],
    repairDate: [{ required: true, message: '维修日期不能为空', trigger: 'blur' }],
    repairCost: [{ required: true, message: '维修费用不能为空', trigger: 'blur' }],
    repairReason: [{ required: true, message: '维修原因不能为空', trigger: 'blur' }],
    userId: [{ required: true, message: '跟进人不能为空', trigger: 'blur' }]
  })
  const formRef = ref() // 表单 Ref

  /** 打开弹窗 */
  const open = async (type: string, id?: number) => {
    dialogVisible.value = true
    dialogTitle.value = t('action.' + type)
    formType.value = type
    resetForm()

    if (id) {
      formLoading.value = true
      try {
        formData.value = await AssetRepairApi.getAssetRepair(id)

      } finally {
        formLoading.value = false
      }
    }
  }


  defineExpose({ open }) // 提供 open 方法，用于打开弹窗

  const assetList = ref([]) // 资产列表
  const getAssetList = async () => {
    try {
      const res = await AssetInfoApi.getAssetInfoPage({})
      assetList.value = res.list || []
    } catch (error) {
      console.error('获取资产列表失败', error)
    }
  }

  const handleAssetChange = (selectedName: string) => {
    const selectedAsset = assetList.value.find(asset => asset.assetName === selectedName)
    if (selectedAsset) {
      formData.value.assetCategory = selectedAsset.assetCategory
      formData.value.assetBrand = selectedAsset.assetBrand
      formData.value.model = selectedAsset.model
    }
  }


  /** 提交表单 */
  const emit = defineEmits(['success']) // 定义 success 事件，用于操作成功后的回调
  const submitForm = async () => {
    // 校验表单
    await formRef.value.validate()
    // 提交请求
    formLoading.value = true
    try {
      const data = formData.value as unknown as AssetRepairVO
      if (formType.value === 'create') {
        await AssetRepairApi.createAssetRepair(data)
        message.success(t('common.createSuccess'))
      } else {
        await AssetRepairApi.updateAssetRepair(data)
        message.success(t('common.updateSuccess'))
      }
      dialogVisible.value = false
      // 发送操作成功的事件
      emit('success')
    } finally {
      formLoading.value = false
    }
  }

  /** 重置表单 */
  const resetForm = () => {
    formData.value = {
      id: undefined,
      assetName: undefined,
      assetCategory: undefined,
      assetBrand: undefined,
      model: undefined,
      repairDate: undefined,
      repairCost: undefined,
      repairReason: undefined,
      userId: undefined,
      userName: undefined,
      recordTime: undefined,
    }
    formRef.value?.resetFields()
  }


  onMounted(() => {
    getAssetList()
  })

  /** 员工被点击事件 */
  const handleNodeChange = async (row) =>{
    console.log('【UserSelect】选中用户对象:', row) // 打印完整对象
    console.log('用户ID:', row?.id)
    console.log('用户昵称:', row?.nickname)
    formData.value.userId = row.id
    formData.value.userName = row.nickname
  }
  </script>
